package com.wbw.ssb.service.impl;

import cn.hutool.core.date.DateUtil;
import com.wbw.ssb.common.api.ResultCode;
import com.wbw.ssb.dao.TemperatureDao;
import com.wbw.ssb.exception.Asserts;
import com.wbw.ssb.mbg.entity.Smog;
import com.wbw.ssb.mbg.entity.Temperature;
import com.wbw.ssb.mbg.mapper.SmogDynamicSqlSupport;
import com.wbw.ssb.mbg.mapper.TemperatureDynamicSqlSupport;
import com.wbw.ssb.mbg.mapper.TemperatureMapper;
import com.wbw.ssb.service.TemperatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;
import static org.mybatis.dynamic.sql.SqlBuilder.isGreaterThan;

/**
 * @Author: guibo
 * @Description:
 * @Date: Created in 16:14 2021/5/25
 * @Modified By:
 */
@Service
public class TemperatureServiceImpl implements TemperatureService {
    @Autowired
    TemperatureDao temperatureDao;
    @Autowired
    TemperatureMapper temperatureMapper;
    @Override
    public LinkedHashMap<String, Double> getToday(Long granaryNumber) {
        LinkedHashMap<String,Double> dateDoubleHashMap = new LinkedHashMap<>();
        List<Temperature>  temperatureList=  temperatureDao.getToday(granaryNumber);
        temperatureList.forEach(i->dateDoubleHashMap.put(DateUtil.formatDateTime(i.getDataTime()),i.getTemperature()));
        return dateDoubleHashMap;

    }
    @Override
    public Temperature getNow(Long granaryNumber) {
        Date twoMinuteAgo = new Date((new Date()).getTime()-120000);
        List<Temperature> temperatureList =  temperatureMapper.select(c->c
                .where(TemperatureDynamicSqlSupport.granaryNumber,isEqualTo(granaryNumber))
                .and(TemperatureDynamicSqlSupport.dataTime,isGreaterThan(twoMinuteAgo))
                .orderBy(TemperatureDynamicSqlSupport.id.descending())
                .limit(1)
        );
        if (temperatureList.isEmpty()){
            return new Temperature();
        }
        return temperatureList.get(0);
    }
}
